package com.custom.lotterydraw


import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import kotlin.random.Random


/**
 * @description：TODO
 * @Author MRyan
 * @Date 2020/3/26 8:22
 * @Version 1.0
 */
class CustomLotteryDraw : View {
    private var mPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
        strokeWidth = mStrokWidth
    }
    private var mCustomWidth = 0
    private var mCustomHeight = 0
    private var mCustomSize = 0
    private var mRectSize = 0//矩形的宽和高（矩形为正方形）
    private var mRects: ArrayList<RectF> = ArrayList()
    private val mStrokWidth = 5f //矩形的描边宽度
    private var isfinish: Boolean? = true//是否结束
    private var isdrawLottery: Boolean? = false//是否绘制最后的奖品
    private val mLuckStr =
        arrayOf(
            "性感美照一份",
            "真可惜！啧啧啧",
            "一起睡觉！！！",
            "看！什么都没有！",
            "一个大大的拥抱",
            "咳咳！看图！来吧",
            "运气有点不好哈",
            "一个大大的么么哒"
        ) //这是抽奖的提示信息


    private val mImgs = intArrayOf(
        R.drawable.png,
        R.drawable.timgnull,
        R.drawable.sleep,
        R.drawable.timgnull,
        R.drawable.baobao,
        R.drawable.talk,
        R.drawable.timgnull,
        R.drawable.kiss,
        R.drawable.timg
    )
    private var mRepeatCount = 4 //转的圈数

    private var mLuckNum = 3 //最终中奖位置

    private var mPosition = -1 //抽奖块的位置

    private var mStartLuckPosition = 0 //开始抽奖的位置
    private var mClickStartFlag = false //是否点击中间矩形的标记


    private val mItemColor =
        intArrayOf(Color.parseColor("#FFFF00"), Color.parseColor("#800080")) //矩形的颜色


    constructor(context: Context?) : super(context)
    constructor(
        context: Context,
        attrs: AttributeSet?
    ) : super(context, attrs) {
        init()

    }

    private fun init() {
        mRepeatCount = 4 //转的圈数

        mLuckNum = Random.nextInt(0, 8) //最终中奖位置

        mPosition = -1 //抽奖块的位置

        mStartLuckPosition = 0 //开始抽奖的位置
    }

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr)

    init {
        // 禁用硬件加速
        setLayerType(LAYER_TYPE_SOFTWARE, null)
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        mCustomWidth = MeasureSpec.getSize(widthMeasureSpec)
        mCustomHeight = MeasureSpec.getSize(heightMeasureSpec)
        mCustomSize = Math.min(mCustomHeight, mCustomWidth)
        setMeasuredDimension(mCustomSize, mCustomSize)
        /*   Log.e("setMeasuredDimension", mCustomSize.toString())*/
        mRectSize = mCustomSize / 3//获取矩形的宽和高
        Log.e("执行", "onMeasure")

    }


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        initRect()
        Log.e("执行", "onSizeChanged")
    }

    /**
     * 加载矩形数据
     */
    private fun initRect() {
        //加载前三个矩形
        for (x in 0..2) {
            val left = x * mRectSize.toFloat()
            val top = 0f
            val right = (x + 1) * mRectSize.toFloat()
            val bottom = mRectSize.toFloat()
            val rectF = RectF(left, top, right, bottom)
            mRects.add(rectF)
        }
        //加载第四个
        mRects.add(
            RectF(
                (mCustomWidth - mRectSize).toFloat(),
                mRectSize.toFloat(),
                mCustomWidth.toFloat(),
                (mRectSize * 2).toFloat()
            )
        )
        //加载第五~七个
        for (y in 3 downTo 1) {
            val left = mCustomWidth - (4 - y) * mRectSize.toFloat()
            val top = mRectSize * 2.toFloat()
            val right = (y - 3) * mRectSize + mCustomWidth.toFloat()
            val bottom = mRectSize * 3.toFloat()
            val rectF = RectF(left, top, right, bottom)
            mRects.add(rectF)
        }
        //加载第八个
        mRects.add(RectF(0f, mRectSize.toFloat(), mRectSize.toFloat(), (mRectSize * 2).toFloat()))
        //加载第九个
        mRects.add(
            RectF(
                mRectSize.toFloat(),
                mRectSize.toFloat(),
                (mRectSize * 2).toFloat(),
                (mRectSize * 2).toFloat()
            )
        )
        /* for (i in mRects.indices) {
             Log.e("setMeasuredDimension", mRects[i].toString());
         }*/

    }


    override fun onDraw(canvas: Canvas?) {
        if (canvas != null) {
            drawRects(canvas)
            drawImages8(canvas)
            if (this.isdrawLottery!!) {
                drawImages(canvas)
            }

        }
    }

    /**
     * 画矩形
     * @param canvas
     */
    private fun drawRects(canvas: Canvas) {
        for (x in mRects.indices) {
            val rectF = mRects[x]
            if (x == 8) {
                mPaint.color = Color.WHITE
                canvas.drawRect(rectF, mPaint)
            } else {
                if (mPosition == x) {
                    mPaint.color = Color.parseColor("#ffffff")
                } else {
                    mPaint.color = mItemColor[x % 2]
                }
                canvas.drawRect(rectF, mPaint)
            }
        }
    }

    /**
     * 判断触摸范围是否在指定区域进行
     */
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) {
            mClickStartFlag = mRects[8].contains(event.x, event.y)
            /*  Log.e("event","${event.x}+${event.y}")
              Log.e("event","${mRects[8]}")*/
            return true
        }
        if (event.action == MotionEvent.ACTION_UP) {
            if (mClickStartFlag) {
                if (mRects[8].contains(event.x, event.y)) {
                    //如果结束了上次才能开始下一次
                    if (isfinish == true) {
                        //没完成 正在进行中
                        onisfinish.isonFinished(false, "")
                        //判断只有手指落下和抬起都在中间的矩形内才开始抽奖
                        starAnim()
                    } else {

                    }
                }
                mClickStartFlag = false
            }
        }
        return super.onTouchEvent(event)
    }


    fun starAnim() {
        mLuckNum = Random.nextInt(0, 8)
        val valueAnimator =
            ValueAnimator.ofInt(mStartLuckPosition, mRepeatCount * 8 + mLuckNum)
                .setDuration(15000)
        valueAnimator.addUpdateListener { animation ->
            val position = animation.animatedValue as Int
            setPosition(position % 8)
            //没结束 所以不能在过程中再次抽奖
            isfinish = false
        }
        valueAnimator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                //将结束后将获奖的位置给下一次开始抽奖的位置
                mStartLuckPosition = mLuckNum
                //重新定义获奖位置
                isdrawLottery = true
                //结束了 可以再次抽奖
                isfinish = true
                onisfinish.isonFinished(true, mLuckStr[mLuckNum])


            }
        })
        valueAnimator.start()
        isdrawLottery = false
    }


    fun setPosition(position: Int) {
        mPosition = position
        postInvalidate()
    }

    /**
     * 绘制点击抽奖按钮
     * @param canvas
     */
    private fun drawImages8(canvas: Canvas) {
        val rectF = mRects[8]
        val left = rectF.centerX() - mRectSize / 2
        val top = rectF.centerY() - mRectSize / 2
        canvas.drawBitmap(
            Bitmap.createScaledBitmap(
                BitmapFactory.decodeResource(resources, mImgs[8]),
                mRectSize,
                mRectSize,
                false
            ), left, top, null
        )

    }

    /**
     * 绘制抽奖后获奖图片
     * @param canvas
     */
    private fun drawImages(canvas: Canvas) {
        val rectF = mRects[mLuckNum]
        val left = rectF.centerX() - mRectSize / 2
        val top = rectF.centerY() - mRectSize / 2
        canvas.drawBitmap(
            Bitmap.createScaledBitmap(
                BitmapFactory.decodeResource(resources, mImgs[mLuckNum]),
                mRectSize,
                mRectSize,
                false
            ), left, top, null
        )
    }

    /**
     * 暴露接口 是否完成
     */
    interface OnisFinish {
        fun isonFinished(isfinished: Boolean, luckname: String)
    }

    private lateinit var onisfinish: OnisFinish;

    fun setIsonFinishListener(onisFinish: OnisFinish) {
        this.onisfinish = onisFinish
    }


}